<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/6/29
 * Time: 15:23
 */

namespace app\commi\controller;

use think\Db;
use think\Request;

class Matchmember extends Base
{
    /**
     * 参赛人员列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        $match_id = Db::table('up_match')
            ->where('match_committee_id', session('com_id'))
            ->where('match_member_id', session('cm_id'))
            ->value('match_id');
        if(request()->isAjax ()){
            $user_keyword = trim(input('user_keyword'), ' ');
            $match_keyword = trim(input('match_keyword'), ' ');
            $apply_start_time = input('apply_start_time');
            $apply_end_time = input('apply_end_time');
            $ma_sgin_status = input('ma_sgin_status');
            $ma_baodao_status = input('ma_baodao_status');
            $user_gender = input('user_gender');
            $club_id = input('club_id');
            
            $where['ma_match_id'] = $match_id;
            $where['ma_role'] = 1;
            // 注册手机号/ID/队员名称
            if(isset($user_keyword) && $user_keyword != ''){
                $where['user_phone|user_create_id|ma_user_name'] = ['like', '%' . $user_keyword . '%'];
            }
            // 赛事ID/赛事名称
            if(isset($match_keyword) && $match_keyword != ''){
                $where['match_id|match_title'] = ['like', '%' . $match_keyword . '%'];
            }
            // 报名时间
            if(isset($apply_start_time) && $apply_start_time != '' && isset($apply_end_time) && $apply_end_time != ''){
                $where['ma_time'] = ['between', [$apply_start_time, $apply_end_time]];
            }
            if(isset($apply_start_time) && $apply_start_time != '' && isset($apply_end_time) && $apply_end_time == ''){
                $where['ma_time'] = ['>=', $apply_start_time];
            }
            if(isset($apply_start_time) && $apply_start_time == '' && isset($apply_end_time) && $apply_end_time != ''){
                $where['ma_time'] = ['<=', $apply_end_time];
            }
            // 签到状态
            if(isset($ma_sgin_status) && $ma_sgin_status != ''){
                $where['ma_sgin_status'] = $ma_sgin_status;
            }
            // 报到状态
            if(isset($ma_baodao_status) && $ma_baodao_status != ''){
                $where['ma_baodao_status'] = $ma_baodao_status;
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['ma_user_gender'] = $user_gender;
            }
            // 俱乐部
            if(isset($club_id) && $club_id != ''){
                $where['club_id'] = $club_id;
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('match_apply_info')
                ->join('up_u_user', 'ma_user_id = user_id', 'left')
                ->join('up_club', 'ma_club_id = club_id', 'left')
                ->join('up_match_group', 'mg_id = ma_group', 'left')
                ->join('up_match', 'ma_match_id = match_id', 'left')
                ->where($where)
                ->count();// 获取总条数
            $count2 = Db::name('match_apply_info')
                ->join('up_u_user', 'ma_user_id = user_id', 'left')
                ->join('up_club', 'ma_club_id = club_id', 'left')
                ->join('up_match_group', 'mg_id = ma_group', 'left')
                ->join('up_match', 'ma_match_id = match_id', 'left')
                ->where($where)
                ->column('ma_id');// 获取总条数
            $lists = Db::name('match_apply_info')
                ->join('up_u_user', 'ma_user_id = user_id', 'left')
                ->join('up_club', 'ma_club_id = club_id', 'left')
                ->join('up_match_group', 'mg_id = ma_group', 'left')
                ->join('up_match', 'ma_match_id = match_id', 'left')
                ->field('ma_id, ma_user_name, user_phone, user_create_id, ma_user_gender, ma_user_email, 
                ma_user_call, club_name, ma_match_id, match_title, mg_name, ma_total_price,  
                ma_sgin_status, ma_baodao_status, ma_time, ma_date, match_status')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('ma_time desc')
                ->select();
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $lists]);
        }
        $club = Db::table('up_match_apply_info')
            ->join('up_club', 'club_id = ma_club_id', 'left')
            ->field('club_id, club_name')
            ->where('ma_match_id', $match_id)
            ->group('ma_club_id')
            ->select();
        $this->assign([
            'club' => $club
        ]);
        return $this->fetch();
    }
    
    /**
     * 报名详情
     * @return \think\response\Json
     */
    public function memberDetail(){
        $ma_id = input('ma_id');
        $detail = Db::table('up_match_apply_info')
            ->join('up_match', 'match_id = ma_match_id', 'left')
            ->join('up_u_user uuu1', 'uuu1.user_id = ma_user_id', 'left')
            ->join('up_club', 'ma_club_id = club_id', 'left')
            ->join('up_match_group', 'ma_group = mg_id', 'left')
            ->join('up_u_user uuu2', 'ma_hexiao_user_id = uuu2.user_id', 'left')
            ->where('ma_id', $ma_id)
            ->field('ma_user_name, ma_user_gender, ma_user_ID_number, ma_user_birthday, 
            ma_user_email, ma_user_call, ma_user_urg_phone, club_name, ma_coach, ma_lingd, 
            ma_user_sailing_time, ma_fan_code, ma_boat_code, ma_match_id, match_title, 
            ma_total_price, ma_cost_info_id, mg_name, ma_baodao_time, 
            uuu2.user_username hexiao_name, ma_sgin_time, ma_sgin_addr, ma_user_fanlian_ID, ma_user_fanxie_ID')
            ->find();
        $info = Db::table('up_match_cost_info')
            ->join('up_match_cost', 'mc_id = mi_cost_id', 'left')
            ->where('mi_id', 'IN', $detail['ma_cost_info_id'])
            ->field('mc_name, mi_price')
            ->select();
        $detail['cost_info'] = $info;
        $this->assign([
            'detail' => $detail
        ]);
        return $this->fetch('matchmember/memberdetail');
    }
    
    /**
     * 编辑报名信息
     * @return mixed|\think\response\Json
     */
    public function memberEdit(){
        $ma_id = input('ma_id');
        $apply = Db::table('up_match_apply_info')
            ->where('ma_id', $ma_id)
            ->field('ma_club_id, ma_lingd, ma_coach, ma_group, ma_fan_code, ma_boat_code, ma_match_id, 
            ma_real_pay_user_id')
            ->find();
        if(Request::instance()->isPost()){
            $ma_club_id = input('ma_club_id');
            $ma_lingd = input('ma_lingd');
            $ma_coach = input('ma_coach');
            $ma_group = input('ma_group');
            $ma_fan_code = input('ma_fan_code');
            $ma_boat_code = input('ma_boat_code');
            if($apply['ma_group'] != $ma_group){
                $group_num = Db::table('up_match_apply_group')
                    ->where('mag_match_id', $apply['ma_match_id'])
                    ->where('mag_group_id', $ma_group)
                    ->field('mag_apply_num, mag_already_num')
                    ->find();
                if($group_num['mag_already_num'] >= $group_num['mag_apply_num']){
                    return json(['code' => 100, 'msg' => '该组别报名人数已满']);
                }
            }
            $update = [
                'ma_club_id' => $ma_club_id,
                'ma_lingd' => $ma_lingd,
                'ma_coach' => $ma_coach,
                'ma_group' => $ma_group,
                'ma_fan_code' => $ma_fan_code,
                'ma_boat_code' => $ma_boat_code
            ];
            Db::startTrans();
            try{
                Db::table('up_match_apply_info')
                    ->where('ma_real_pay_user_id', $apply['ma_real_pay_user_id'])
                    ->where('ma_match_id', $apply['ma_match_id'])
                    ->update($update);
                if($apply['ma_group'] != $ma_group){
                    // 原组别报名人数减一
                    Db::table('up_match_apply_group')
                        ->where('mag_match_id', $apply['ma_match_id'])
                        ->where('mag_group_id', $apply['ma_group'])
                        ->setDec('mag_already_num');
                    // 现组别报名人数加一
                    Db::table('up_match_apply_group')
                        ->where('mag_match_id', $apply['ma_match_id'])
                        ->where('mag_group_id', $ma_group)
                        ->setInc('mag_already_num');
                }
                Db::commit();
                return json(['code' => 200, 'msg' => '编辑成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        
        // 俱乐部
        $club = Db::table('up_club')
            ->field('club_id, club_name')
            ->where('club_status', 1)
            ->select();
        // 组别
        $group = Db::table('up_match_apply_group')
            ->join('up_match_group', 'mg_id = mag_group_id', 'left')
            ->where('mag_match_id', $apply['ma_match_id'])
            ->field('mag_group_id, mg_name')
            ->select();
        $this->assign([
            'apply' => $apply,
            'club' => $club,
            'group' => $group,
            'ma_id' => $ma_id
        ]);
        $lose = $this->lostTime();
        if($lose == 1){
            return $this->fetch('/lose');
        }else{
            return $this->fetch('matchmember/memberedit');
        }
    }
    
    /**
     * 船员
     * @return mixed|\think\response\Json
     */
    public function memberOther(){
        if(request()->isAjax ()){
            $user_keyword = trim(input('user_keyword'), ' ');
            $user_gender = input('user_gender');
            $info = Db::table('up_match_apply_info')
                ->where('ma_id', session('ma_id'))
                ->field('ma_user_id, ma_match_id')
                ->find();
            
            $where['ma_real_pay_user_id'] = $info['ma_user_id'];
            $where['ma_match_id'] = $info['ma_match_id'];
            $where['ma_role'] = 2;
            
            // 注册手机号/ID/队员名称
            if(isset($user_keyword) && $user_keyword != ''){
                $where['user_phone|user_create_id|ma_user_name'] = ['like', '%' . $user_keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['ma_user_gender'] = $user_gender;
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('match_apply_info')
                ->join('up_u_user', 'ma_user_id = user_id', 'left')
                ->join('up_match', 'ma_match_id = match_id', 'left')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('match_apply_info')
                ->join('up_u_user', 'ma_user_id = user_id', 'left')
                ->join('up_match', 'ma_match_id = match_id', 'left')
                ->field('ma_id, ma_user_name, user_phone, user_create_id, ma_user_gender, ma_user_email, 
                ma_user_call, match_status, ma_user_urg_phone, ma_user_ID_number')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('ma_time desc')
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $ma_id = input('ma_id');
        if(isset($ma_id) && $ma_id != ''){
            session('ma_id', $ma_id);
        }
        $match_status = Db::table('up_match_apply_info')
            ->join('up_match', 'match_id = ma_match_id', 'left')
            ->where('ma_id', session('ma_id'))
            ->value('match_status');
        $this->assign([
            'match_status' => $match_status
        ]);
        return $this->fetch('matchmember/memberother');
    }
    
    /**
     * 添加队员
     * @return mixed|\think\response\Json
     */
    public function otherAdd(){
        if(Request::instance()->isPost()){
            $user_id = input('user_id');
            $user_info = Db::table('up_u_user')
                ->field('user_club_id, user_real_check')
                ->where('user_id', $user_id)
                ->find();
            if($user_info['user_real_check'] == 1){
                return json(['code' => 100, 'msg' => '该用户尚未实名认证']);
            }
            $info = Db::table('up_match_apply_info')
                ->where('ma_id', session('ma_id'))
                ->field('ma_match_id, ma_lingd, ma_coach, ma_group, ma_fan_code, ma_boat_code, 
                ma_time, ma_date, ma_total_price, ma_cost_info_id, ma_match_cate, ma_user_id, 
                ma_real_pay_user_id, ma_order_num, ma_apply_status, ma_club_id')
                ->find();
            $user = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->field('user_phone, user_real_name, user_gender, user_birthday, user_ID_number, user_call, 
            user_email, user_urg_phone, user_sailing_time, user_fanlian_ID, user_fanxie_ID')
                ->find();
            $match = Db::table('up_match')
                ->field('match_start_time')
                ->where('match_id', $info['ma_match_id'])
                ->find();
            // 已报名本赛事
            $thisMatch = Db::table('up_match_apply_info')
                ->where('ma_user_id', $user_id)
                ->where('ma_match_id', $info['ma_match_id'])
                ->where('ma_apply_status', 2)
                ->find();
            if($thisMatch){
                return json(['code' => 100, 'msg' => '该用户已报名本场比赛']);
            }
            // 其他比赛
            $otherMatch = Db::table('up_match_apply_info')
                ->join('up_match', 'match_id = ma_match_id', 'left')
                ->where('ma_user_id', $user_id)
                ->where('match_end_time', '>', $match['match_start_time'])
                ->where('match_id', 'NEQ', $info['ma_match_id'])
                ->where('ma_apply_status', 2)
                ->field('match_id')
                ->find();
            if($otherMatch) return json(['status' => 0, 'msg' => '该用户已报名其他有冲突的赛事']);
            $insert = [
                'ma_user_id' => $user_id,
                'ma_match_id' => $info['ma_match_id'],
                'ma_total_price' => $info['ma_total_price'],
                'ma_cost_info_id' => $info['ma_cost_info_id'],
                'ma_club_id' => $info['ma_club_id'],
                'ma_lingd' => $info['ma_lingd'],
                'ma_coach' => $info['ma_coach'],
                'ma_group' => $info['ma_group'],
                'ma_fan_code' => $info['ma_fan_code'],
                'ma_boat_code' => $info['ma_boat_code'],
                'ma_role' => 2,
                'ma_real_pay_user_id' => $info['ma_real_pay_user_id'],
                'ma_time' => $info['ma_time'],
                'ma_date' => $info['ma_date'],
                'ma_match_cate' => $info['ma_match_cate'],
                'ma_order_num' => $info['ma_order_num'],
                'ma_apply_status' => $info['ma_apply_status'],
                'ma_user_name' => $user['user_real_name'],
                'ma_user_gender' => $user['user_gender'],
                'ma_user_birthday' => $user['user_birthday'],
                'ma_user_ID_number' => $user['user_ID_number'],
                'ma_user_call' => $user['user_call'],
                'ma_user_email' => $user['user_email'],
                'ma_user_urg_phone' => $user['user_urg_phone'],
                'ma_user_sailing_time' => $user['user_sailing_time'],
                'ma_user_fanlian_ID' => $user['user_fanlian_ID'],
                'ma_user_fanxie_ID' => $user['user_fanxie_ID']
            ];
            $res = Db::table('up_match_apply_info')->insert($insert);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $user = Db::table('up_u_user')
            ->where('user_status', 1)
            ->field('user_id, user_real_name, user_phone')
            ->select();
        $this->assign([
            'user' => $user
        ]);
        $lose = $this->lostTime();
        if($lose == 1){
            return $this->fetch('/lose');
        }else{
            return $this->fetch('matchmember/otheradd');
        }
    }
    
    /**
     * 编辑船员信息
     * @return mixed|\think\response\Json
     */
    public function otherEdit(){
        $ma_id = input('ma_id');
        if(Request::instance()->isPost()){
            $user_real_name = trim(input('user_real_name'), ' ');
            $user_gender = input('user_gender');
            $user_birthday = input('user_birthday');
            $user_ID_number = trim(input('user_ID_number'), ' ');
            $user_call = trim(input('user_call'), ' ');
            $user_email = trim(input('user_email'), ' ');
            $user_urg_phone = trim(input('user_urg_phone'), ' ');
            $user_sailing_time = trim(input('user_sailing_time'), ' ');
            $ma_user_fanlian_ID = trim(input('ma_user_fanlian_ID'), ' ');
            $ma_user_fanxie_ID = trim(input('ma_user_fanxie_ID'), ' ');
            $user_id = input('user_id');
            $update = [
                'ma_user_name' => $user_real_name,
                'ma_user_gender' => $user_gender,
                'ma_user_birthday' => $user_birthday,
                'ma_user_ID_number' => $user_ID_number,
                'ma_user_call' => $user_call,
                'ma_user_email' => $user_email,
                'ma_user_urg_phone' => $user_urg_phone,
                'ma_user_sailing_time' => $user_sailing_time,
                'ma_update_time' => date('Y-m-d H:i:s'),
                'ma_user_fanlian_ID' => $ma_user_fanlian_ID,
                'ma_user_fanxie_ID' => $ma_user_fanxie_ID
            ];
            $res = Db::table('up_match_apply_info')->where('ma_id', $ma_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $user = Db::table('up_match_apply_info')
            ->join('up_u_user', 'user_id = ma_user_id', 'left')
            ->where('ma_id', $ma_id)
            ->field('user_phone, ma_user_name, ma_user_gender, ma_user_birthday, ma_user_ID_number, ma_user_call, 
            ma_user_email, ma_user_urg_phone, ma_user_sailing_time, user_id, ma_user_fanlian_ID, ma_user_fanxie_ID')
            ->find();
        $this->assign([
            'user' => $user,
            'ma_id' => $ma_id
        ]);
        $lose = $this->lostTime();
        if($lose == 1){
            return $this->fetch('/lose');
        }else{
            return $this->fetch('matchmember/otheredit');
        }
    }
    
    /**
     * 删除
     * @return \think\response\Json
     */
    public function otherDel(){
        $lose = $this->lostTime();
        if($lose == 1){
            return json(['code' => 100, 'msg' => '账号已过期，非法操作']);
        }
        $ma_id = input('id');
        $res = Db::table('up_match_apply_info')->delete($ma_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $ids = input('ids');
        if($ids == ''){
            return json(['code' => 100, 'msg' => '没有需要导出的数据']);
        }
        $order_num = Db::table('up_match_apply_info')
            ->where('ma_id', 'IN', $ids)
            ->column('ma_order_num');
        $lists = Db::name('match_apply_info')
            ->join('up_u_user', 'ma_user_id = user_id', 'left')
            ->join('up_club', 'ma_club_id = club_id', 'left')
            ->join('up_match_group', 'mg_id = ma_group', 'left')
            ->join('up_match', 'ma_match_id = match_id', 'left')
            ->where('ma_order_num', 'IN', $order_num)
            ->field('ma_user_name, ma_user_gender, ma_user_birthday, ma_user_ID_number, ma_user_fanlian_ID, 
            ma_user_fanxie_ID, ma_user_call, ma_user_email, ma_user_urg_phone, ma_user_sailing_time, 
            match_title, ma_cost_info_id, club_name, ma_lingd, ma_coach, mg_name, ma_fan_code, ma_boat_code, 
            ma_role, ma_time, ma_sgin_status, ma_baodao_status, user_create_id, ma_baodao_time, 
            ma_sgin_time, ma_sgin_addr, user_phone, ma_total_price')
            ->select();
        foreach($lists as $k => $v){
            // 性别
            $lists[$k]['gender'] = $v['ma_user_gender'] == 1 ? '男' : '女';
            // 角色
            $lists[$k]['role'] = $v['ma_role'] == 1 ? '船长' : '船员';
            // 报到状态
            $lists[$k]['baodao'] = $v['ma_baodao_status'] == 1 ? '未报到' : '已报到';
            // 签到状态
            $lists[$k]['sgin'] = $v['ma_sgin_status'] == 1 ? '未签到' : '已签到';
            // 手机号
            $lists[$k]['user_phone'] = "\t".$v['user_phone']."\t";
            // 电话
            $lists[$k]['ma_user_call'] = "\t".$v['ma_user_call']."\t";
            // 紧急联系人电话
            $lists[$k]['ma_user_urg_phone'] = "\t".$v['ma_user_urg_phone']."\t";
            // 用户ID
            $lists[$k]['user_create_id'] = "\t".$v['user_create_id']."\t";
            // 身份证号
            $lists[$k]['ma_user_ID_number'] = "\t".$v['ma_user_ID_number']."\t";
            // 处理特殊字符串
            $user_name = json_encode($v['ma_user_name']);
            $name = preg_replace("/\\\u[ed][0-9a-f]{3}\\\u[ed][0-9a-f]{3}/", "*", $user_name);//将特殊字符串替换成*
            $lists[$k]['ma_user_name'] = json_decode($name);
            // 费用明细
            if($v['ma_cost_info_id']){
                $cost = Db::table('up_match_cost_info')
                    ->join('up_match_cost', 'mi_cost_id = mc_id', 'left')
                    ->where('mi_id', 'IN', $v['ma_cost_info_id'])
                    ->field('mi_price, mc_name')
                    ->select();
                $str = '';
                foreach($cost as $kk => $vv){
                    $str .= $vv['mc_name'] . ':' . $vv['mi_price'] . ',';
                }
                $lists[$k]['cost_info'] = trim($str, ',');
            }else{
                $lists[$k]['cost_info'] = '';
            }
            
        }
        $cellname = [
            ['user_create_id', '用户ID', 15, 'LEFT'],
            ['ma_user_name', '姓名', 15, 'LEFT'],
            ['user_phone', '手机号', 20, 'LEFT'],
            ['gender', '性别', 10, 'LEFT'],
            ['ma_user_birthday', '出生日期', 15, 'LEFT'],
            ['ma_user_ID_number', '身份证号', 20, 'LEFT'],
            ['ma_user_fanlian_ID', '世界帆联ID', 15, 'LEFT'],
            ['ma_user_fanxie_ID', '国家帆协ID', 15, 'LEFT'],
            ['ma_user_call', '电话', 20, 'LEFT'],
            ['ma_user_email', '邮箱', 30, 'LEFT'],
            ['ma_user_urg_phone', '紧急联系人手机号', 20, 'LEFT'],
            ['ma_user_sailing_time', '航海起航时间', 20, 'LEFT'],
            ['match_title', '赛事', 20, 'LEFT'],
            ['club_name', '俱乐部', 25, 'LEFT'],
            ['ma_lingd', '领队', 10, 'LEFT'],
            ['ma_coach', '教练', 10, 'LEFT'],
            ['mg_name', '组别', 15, 'LEFT'],
            ['ma_fan_code', '帆号', 15, 'LEFT'],
            ['ma_boat_code', '船号', 15, 'LEFT'],
            ['role', '角色', 10,'LEFT'],
            ['ma_time', '报名时间', 20,'LEFT'],
            ['baodao', '报到状态', 15,'LEFT'],
            ['ma_baodao_time', '报到时间', 20,'LEFT'],
            ['sgin', '签到状态', 15,'LEFT'],
            ['ma_sgin_time', '签到时间', 20,'LEFT'],
            ['ma_sgin_addr', '签到地址', 70,'LEFT'],
            ['ma_total_price', '总费用', 10,'LEFT'],
            ['cost_info', '费用明细', 50,'LEFT']
        ];
        $res = exportExcel('报名列表', 'ApplyMember', $cellname, $lists);
        return json($res);
    }
}